<style scoped>
.item-yc{
  width: 300px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow:ellipsis;
}
</style>
<template>
  <div>
    <div class="search" style="display: flex">
      <el-input placeholder="请输入查询" style="width: 200px" v-model="searchValue"></el-input>
      <div style="display: flex;margin-left: 10px">
        <el-button type="primary" plain @click="handleAdd">新增</el-button>
        <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      </div>
    </div>



    <div class="table">
      <el-table :data="tableData" strip @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="70" align="center" sortable></el-table-column>
        <el-table-column label="图片">
          <template v-slot="scope">
            <div style="display: flex; align-items: center">
              <el-image style="width: 40px; height: 40px; border-radius: 50%" v-if="scope.row?.avatar"
                        :src="visitPath()+ scope.row?.avatar" :preview-src-list="imgListFun(scope.row?.imageList)"></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" width="120"></el-table-column>
        <el-table-column prop="price" label="起步价"></el-table-column>
        <el-table-column prop="location" label="所在地" width="140"></el-table-column>
        <el-table-column prop="address" label="详情地址" width="180"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column  label="位置描述"  width="320" :show-overflow-tooltip="true">
          <template v-slot="scope">
                <div class="item-yc" style="width: 220px">{{titleListFun(scope.row?.describeList)}}</div>
          </template>
        </el-table-column>
        <el-table-column  label="民宿介绍" width="320" :show-overflow-tooltip="true">
          <template v-slot="scope">
                <div class="item-yc" style="width: 220px">{{titleListFun(scope.row?.introduce)}}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>


    <el-dialog title="民宿" :visible.sync="fromVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="form" label-width="100px" style="padding-right: 10px" :rules="rules" ref="formRef">
        <el-form-item label="酒店名称" maxlength="20" prop="name">
          <el-input v-model="form.name" placeholder="请填写酒店名称"></el-input>
        </el-form-item>
        <el-form-item label="酒店图片">
          <el-upload
              class="avatar-uploader"
              :action="upladPath()"
              :headers="{ token: user.token }"
              list-type="picture"
              :on-success="handleAvatarSuccess"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="起步价" prop="price">
          <el-input v-model="form.price" type="number" maxlength="6" placeholder="请填写起步价"></el-input>
        </el-form-item>
        <el-form-item label="所在地" maxlength="30" prop="location">
          <el-input  v-model="form.location" placeholder="请填写酒店所在地"></el-input>
        </el-form-item>
        <el-form-item label="详情地址"  maxlength="50" prop="address">
          <el-input v-model="form.address"  placeholder="请填写酒店详情地址"></el-input>
        </el-form-item>
        <el-form-item label="位置描述" >
          <el-input v-model="describeList" rows="3" type="textarea" placeholder="位置描述（填写示例：靠近海湾风景号||附近有地铁站||***）"></el-input>
        </el-form-item>
        <el-form-item label="酒店介绍" >
          <el-input v-model="introduce" type="textarea" rows="5" placeholder="酒店介绍（填写示例：酒店介绍/这里是酒店信息描述||位置信息/这里是位置信息描述||***/***）"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {upladPath, visitPath} from "@/Interface/FileApi";
import {addHotel, deleteHotel, deletesHotel, queryHotelPage, updateHotel} from "@/Interface/HotelApi";
import {backLogin, imgListFun, titleListFun} from "@/Config/Tool";
import {queryRoomPage} from "@/Interface/RoomApi";

export default {
  name: "Hotel",
  data() {
    return {
      searchValue:null,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      username: null,
      fromVisible: false,
      form: {
        name:null,
        address:null,
        avatar:null,
        location:null,
        description:null,
        price:0.0,
        describeList:null,//[{title:''}]
        imageList:null,//[{img:'']
        introduce:null ,//[{title:'',content:''}]
      },
      describeList:null,
      introduce:null,
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        name: [
          { required: true, message: '酒店名称不能为空', trigger: 'blur' },
        ],
        location: [
          { required: true, message: '所在地不能为空', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
        ],
        address: [
          { required: true, message: '详情地址不能为空', trigger: 'blur' },
        ],

      },
      ids: []
    }
  },
  created() {
    backLogin("ADMIN")
    this.load(1);
  },
  watch:{
    searchValue(newValue,oldValue){
      if (newValue){
        queryHotelPage({
          limit:10000,
          page:1,
          param:{}
        }).then(res => {
          if (res.code === 200) {
            const result = res.data?.records.filter(item => {
              return Object.values(item).some(val => val?.toString().includes(newValue));
            });
            this.tableData= result;
          } else {
            this.$message.error(res.msg)
          }
        })
      }else {
        this.load(1);
      }
    },
  },
  methods: {
    titleListFun,
    imgListFun,
    visitPath() {
      return visitPath
    },
    upladPath() {
      return upladPath
    },
    handleAdd() {
      this.form = {
        name:null,
        address:null,
        avatar:null,
        location:null,
        description:null,
        price:0.0,
        describeList:[],//[{title:''}]
        imageList:[],//[{img:'']
        introduce:[] ,//[{title:'',content:''}]
      }
      this.fromVisible = true
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.introduce=null;
      this.describeList=null;
      if (this.form.describeList?.length>=1){
        this.form.describeList.map(item=>{
          if (this.describeList){
            this.describeList=this.describeList+"||"+item.title
          }else {
            this.describeList=item.title
          }
        });
      }
      if (this.form.introduce?.length>=1){
        this.form.introduce.map(item=>{
          if (this.introduce){
            this.introduce=this.introduce+"||"+item.title+"/"+item.content
          }else {
            this.introduce=item.title+"/"+item.content
          }
        });
      }
      this.fromVisible = true
    },
    save() {
      let that = this;
      let describeList =[];
      let describeListStr=that.describeList.split("||");
      describeListStr.map(item=>{describeList.push({"title":item||""})})
      that.form.describeList=describeList;

      let introduce =[];
      let introduceStr=that.introduce.split("||");
      introduceStr.map(item=>{
        let titleStr=item.split("/");
        introduce.push({"title":titleStr[0]||"","content":titleStr[1]||""})
      })
      that.form.introduce=introduce;
      that.$refs.formRef.validate((valid) => {
        if (valid) {
          console.log(that.form)
          if (that.form.id){
            updateHotel(this.form).then(res => {
              if (res.code === 200) {
                that.$message.success(res.msg)
                setTimeout(()=>{
                  that.load(1)
                },1000)
                that.fromVisible = false
              } else {
                that.$message.error(res.msg)
              }
            })
          }else {
            addHotel(that.form).then(res=>{
              if (res.code === 200) {
                that.$message.success(res.msg)
                setTimeout(()=>{
                  that.load(1)
                },1000)
                that.fromVisible = false
              } else {
                that.$message.error(res.msg)
              }
            })
          }
        }
      })
    },
    /**
     * 删除接口
     */
    del(id) {
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        deleteHotel({id}).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {
      this.ids = rows.map(v => v.id)
    },
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        deletesHotel({deleteIds: this.ids}).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      queryHotelPage({
        limit:this.pageSize,
        page:this.pageNum,
        param:{}
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data?.records
          this.total = res.data?.total
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    /**
     * 文件上传
     */
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleAvatarSuccess(response, file, fileList) {
      let that = this;
      if (response.code==="200"){
        this.$message.success('上传成功');
        this.form.imageList = this.form.imageList.concat([{"img":response.data.fileName}]);
        that.form.avatar=that.form.imageList[0].img;
      }else {
        that.$message.error("文件上传失败");
      }
    },
  }
}
</script>


